package com.xdh.zzqh.utils

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Canvas
import android.util.Log
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.Toast
import androidx.core.content.FileProvider
import com.xdh.zzqh.R
import com.xdh.zzqh.app.App
import com.xdh.zzqh.app.AppContext
import com.xdh.zzqh.ui.BaseActivity
import java.io.File
import java.io.FileOutputStream
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date

const val APP_ID = "com.xdh.zzqh"

fun sharedViewImage(view: View) {
    val file = saveViewTiFile(view)
    sharedImage(file)
}

private var toast: Toast? = null

fun showToast(msg: String) {
    if (toast == null) {
        toast = Toast.makeText(AppContext, msg, Toast.LENGTH_SHORT)
    } else {
        toast!!.setText(msg)
    }
    toast!!.show()
}

fun dimenById(id: Int) = AppContext.resources.getDimension(id).toInt()
fun stringById(id: Int) = AppContext.resources.getString(id)

private fun saveViewTiFile(view: View, name: String = "shared.png"): File {
    val bitmap = Bitmap.createBitmap(view.width, view.height, Bitmap.Config.ARGB_8888)
    val canvas = Canvas(bitmap)
    view.draw(canvas)

    val file = File(AppContext.filesDir, name)
    Log.d("DEBUG", "${stringById(R.string.fen_xiang_wen_jian)}:${file.path}")
    val output = FileOutputStream(file)
    output.use {
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, output)
        output.flush()
    }
    return file
}

fun currentDate(): String {
    val format = SimpleDateFormat("yyyy/MM/dd")
    return format.format(Date())
}

private fun sharedImage(file: File) {
    val uri = FileProvider.getUriForFile(AppContext, "${APP_ID}.fileprovider", file)
    val intent = Intent(Intent.ACTION_SEND).apply {
        type = "image/png"
        putExtra(Intent.EXTRA_STREAM, uri)
        addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
    }
    BaseActivity.INSTANCE.startActivity(Intent.createChooser(intent, stringById(R.string.fen_xiang_dao)))
}

fun hideSoftKey(activity: Activity) {
    val imm = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    if (!imm.isActive) {
        return
    }
    val view = activity.currentFocus ?: return
    imm.hideSoftInputFromWindow(view.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
}